<!--
 * @Description: Stay hungry,Stay foolish
 * @Author: Huccct
 * @Date: 2023-05-21 16:11:08
 * @LastEditors: Huccct
 * @LastEditTime: 2023-06-01 14:59:11
-->
<script setup lang="ts">
import {
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
} from 'vue'

import { ElMessage } from 'element-plus'

import { reqAllRoleList } from '@/api/acl/role'
import type {
  MenuList,
  MenuResponseData,
  Records,
  RoleData,
  RoleResponseData,
} from '@/api/acl/role/type'
import router from '@/router'
import useLayOutSettingStore from '@/store/modules/setting'
import useUserStore from '@/store/modules/user'
import request from '@/utils/request'

let userStore = useUserStore()
let pageNo = ref<number>(1)

let pageSize = ref<number>(10)

let settingStore = useLayOutSettingStore()

let dialogVisible = ref<boolean>(false)

let RoleParams = reactive<Partial<RoleData>>({
  roleName: '',
  userId :''
})
let timer= ref<any>(null)

onMounted(() => {

    getHasRole()

   timer.value = setInterval(() => {
    getHasRole()
    // clearTimeout(timer.value)
  }, 5000)
})
onBeforeUnmount(() => {
  clearInterval(timer.value)

})

let allRole = ref<Records>([])

let total = ref<number>(0)
let form = ref<any>()

let drawer = ref<boolean>(false)

let menuArr = ref<MenuList>([])

let selectArr = ref<number[]>([])

let tree = ref<any>()
const getHasRole = async (pager = 1) => {
  let res = await reqAllRoleList(pageNo.value, pageSize.value)
  if (res.code === 2000) {
    total.value = res.data.pagination.totalCount
    pageNo.value = res.data.pagination.currentPage
    pageSize.value = res.data.pagination.pageSize
res.data.webSocketUsers.filter((item: any) => {
      if (item.realName !== userStore.username) {
        return item
      }
    })
   
   
    allRole.value = res.data.webSocketUsers.filter((item: any) => {
      if (item.realName !== userStore.username) {
        return item
      }
    })
  
    console.log(allRole.value,res.data.webSocketUsers,userStore.username);
    
  }
}

const sizeHandler = () => {
  getHasRole()
}


const updateRole = (row: RoleData) => {
  dialogVisible.value = true
  // RoleParams.userId = row.id
  // RoleParams.roleName = row.roleName
  Object.assign(RoleParams, row)
  // nextTick(() => {
  //   form.value.clearValidate('roleName')
  // })
  
}
const changepage = (page :string) => {
  console.log(RoleParams);
  
  request
    .post('/message/send-private', {
      fromUserId: userStore.userid,
      fromUsername: userStore.username,
      toUserId:RoleParams.userId,
      toUsername: RoleParams.realName,
      content: page,
      routerPage:"首页",
     
    })
    .then((res) => {
      console.log(res, '发送消息')
  dialogVisible.value = false

    })
}
const validateRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}

const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validateRoleName }],
}

// const save = async () => {
//   await form.value.validate()
//   let res: any = await reqAddOrUpdateRole(RoleParams as RoleData)
//   if (res.code === 200) {
//     ElMessage({
//       type: 'success',
//       message: RoleParams.id ? '更新成功' : '添加成功',
//     })
//     dialogVisible.value = false
//     getHasRole(RoleParams.id ? pageNo.value : 1)
//   }
// }


const defaultProps = {
  children: 'children',
  label: 'name',
}

const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
const removeRole=(row: any)=>{
  Object.assign(RoleParams, row)
  

  request.post('/EmployedManage/update', {
    id: RoleParams.userId,
    ifblock:'已拉黑'
  }).then((res) => {
    console.log(res, '拉黑成功')
      ElMessage({
    type: 'success',
    message: '拉黑成功',
  })
    request
    .post('/message/send-private', {
      fromUserId: userStore.userid,
      fromUsername: userStore.username,
      toUserId:RoleParams.userId,
      toUsername: RoleParams.realName,
      content: '/login',
      routerPage:"拉黑",
     
    })
    .then((res) => {
         console.log(res, '发送消息')
        getHasRole(pageNo.value)
        dialogVisible.value = false

    })

 

  })

}
const removeRole2=(row: any)=>{
  Object.assign(RoleParams, row)
  

  request.post('/EmployedManage/update', {
    id: RoleParams.userId,
    ifblock:'未拉黑'
  }).then((res) => {
    console.log(res, '取消拉黑')
      ElMessage({
    type: 'success',
    message: '取消拉黑',
  })
    request
    .post('/message/send-private', {
      fromUserId: userStore.userid,
      fromUsername: userStore.username,
      toUserId:RoleParams.userId,
      toUsername: RoleParams.realName,
      content: '/login',
      routerPage:"取消拉黑",
     
    })
    .then((res) => {
      console.log(res, '发送消息')
  dialogVisible.value = false
getHasRole(pageNo.value)
    })

      

  })

}
// const handler = async () => {
//   const roleId = RoleParams.id as number

//   let arr = tree.value.getCheckedKeys()
//   let arr1 = tree.value.getHalfCheckedKeys()
//   console.log(arr, arr1)

//   let permissionId = arr.concat(arr1)
//   let res: any = await reqSetPermission(roleId, permissionId)
//   if (res.code === 200) {
//     drawer.value = false
//     ElMessage({
//       type: 'success',
//       message: '分配权限成功',
//     })
//     // window.location.reload()
//   }
// }



</script>
<template>
  <!-- <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="职位搜索">
        <el-input
          placeholder="请你输入搜索职位的关键字"
          v-model="keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
        >
          搜索
        </el-button>
        <el-button size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card> -->
  <el-card style="margin: 10px 0">
    <!-- <el-button type="primary" size="default" icon="Plus" @click="addRole">
      添加职位
    </el-button> -->
    <el-table border style="margin: 10px 0" :data="allRole">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column width="100px" label="当前状态" align="center" prop="status"></el-table-column>
      <el-table-column width="100px" label="登录名称" align="center" show-overflow-tooltip prop="realName"></el-table-column>
      <el-table-column width="200px" label="登录时间" align="center" show-overflow-tooltip prop="connectTime"></el-table-column>
      <el-table-column width="200px" label="操作时间" align="center" show-overflow-tooltip prop="lastActivity"></el-table-column>
      <el-table-column  label="当前页面" align="center" show-overflow-tooltip prop="routerPage"></el-table-column>

      <el-table-column width="200px"  label="操作"  align="center">
        <template #="{ row, $index }">
          <!-- <el-button size="small" icon="User" @click="setPermission(row)">
            分配权限
          </el-button> -->
          <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">
            跳转
          </el-button>
       
          <el-popconfirm
            :title="`你确定要拉黑${row.realName}?`"
            width="260px"
            @confirm="removeRole(row)"
            
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                拉黑
              </el-button>
            </template>
</el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
      :background="true" layout="prev, pager, next, jumper , ->, sizes, total, " :total="total"
  @current-change="getHasRole" @size-change="sizeHandler"
      />
       
  </el-card>
  <el-dialog v-model="dialogVisible" :title="RoleParams.id ? '' : '选择页面'">
      <el-button type="primary" size="small" @click="changepage('/home')">首页</el-button>

    <!-- <el-form :rules="rules" ref="form"> -->
      <!-- //按钮 -->
      <!-- <el-form-item label="职位名称" prop="roleName">
        <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
      </el-form-item> -->
    <!-- </el-form> -->
    <!-- <template #footer>
      <el-button size="default" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" size="default" @click="save">确定</el-button>
    </template> -->
  </el-dialog>

  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <template #default>
      <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="selectArr" :props="defaultProps" />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" >确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
